package com.xianyun.site.auth.common.handler;

import com.alibaba.cola.dto.SingleResponse;
import com.xianyun.common.core.utils.ServletUtils;
import com.xianyun.site.auth.common.config.system.LoginPageConfig;
import com.xianyun.site.auth.common.config.system.LoginType;
import com.xianyun.site.auth.common.entity.SecurityLoginUser;
import com.xianyun.site.auth.service.ITokenResultService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录成功处理逻辑
 *
 * @author songyinyin
 * @date 2020/2/25 下午 09:05
 */
@Slf4j
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private ITokenResultService tokenResultService;


    @Autowired
    private LoginPageConfig loginPageConfig;

    /**
     * TODO：使用数据库（Redis）插入的方式取消接口请求响应
     * @param request 结果
     * @param response 响应
     * @param authentication 权限
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        if (response.isCommitted()) {
            log.debug("Response has already been committed");
            return;
        }
        SecurityLoginUser principal = (SecurityLoginUser) authentication.getPrincipal();
        // 不是密码登陆，需要重定向到前端首页
        if (LoginType.EXTEND.equals(principal.getLoginUser().getLoginType())) {
            log.info("第三方登陆，重定向到登录页");
            //生成Token但是不返回具体结果
            tokenResultService.getTokenByUserTokenResult(principal.getLoginUser(),request);
            response.sendRedirect(loginPageConfig.getLoginPage());
            return;
        }
        Map<String, Object> resultMap = new HashMap<>(5);
        resultMap.put("time", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        resultMap.put("flag", "success_login");
        resultMap.putAll(tokenResultService.getTokenByUserTokenResult(principal.getLoginUser(),request));
        ServletUtils.getResultToCallBack(response, SingleResponse.of(resultMap));
    }
}
